package com.cskaoyan.utils;

import com.cskaoyan.bean.common.BaseRespVo;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * 参数校验工具类
 *
 * @Author: zhang
 * @Date: 2022/11/22 15:44
 * @Since: jdk1.8
 */

public class ValidationUtil {
    /**
     * 返回错误信息的方法
     *
     * @param bindingResult 封装的校验结果
     * @return 错误信息
     */
    public static BaseRespVo<Object> processIllegalArgument(BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            assert fieldError != null;
            String field = fieldError.getField();
            Object rejectedValue = fieldError.getRejectedValue();
            String defaultMessage = fieldError.getDefaultMessage();
            String message = "请求参数" + field + "传入的值" + rejectedValue + "有问题-- >" + defaultMessage;
            return BaseRespVo.invalidParameter(message);
        }
        return null;
    }

    public static void validate(BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            assert fieldError != null;
            String field = fieldError.getField();
            Object rejectedValue = fieldError.getRejectedValue();
            String defaultMessage = fieldError.getDefaultMessage();
            String message = "请求参数" + field + "传入的值" + rejectedValue + "有问题-- >" + defaultMessage;
            throw new IllegalArgumentException(message);
        }
    }
}
